#pragma once

#include <iostream>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <strings.h>

#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"

// 基类，规定创建socket的方法
// 提供一个/若干个/固定模式的socket的方法
namespace SocketMudule
{
    class Socket;
    using SockPtr = std::shared_ptr<Socket>;
    using namespace LogMudule;

    class Socket
    {
    public:
        Socket() {}
        virtual ~Socket() = default;
        virtual void SetSocketOpt() = 0;
        virtual void SocketOrDie() = 0;
        virtual bool BindOrDie(int port) = 0;
        virtual bool ListenOrDie() = 0;
        virtual int Accepter(InetAddr *client) = 0;
        virtual void Close() = 0;
        virtual int Recv(std::string *out) = 0;
        virtual int Send(const std::string &in) = 0;
        virtual int fd() = 0;
        // 提供一个创建listensockfd的固定讨论
        void BuildTcpSocketMethod(int port)
        {
            SocketOrDie();
            SetSocketOpt();
            BindOrDie(port);
            ListenOrDie();
        }
    };



    class TcpSocket : public Socket
    {
    public:
        TcpSocket()
        : _sockfd(gdefaultsockfd)
        {}

        TcpSocket(int sockfd)
        : _sockfd(sockfd)
        {}

        virtual ~TcpSocket()
        {}

        virtual void SocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(LogLevel::ERROR) << "create socket failed";
                exit(SOCKET_ERR);
            }
            LOG(LogLevel::DEBUG) << "create socket success";
        }

        virtual void SetSocketOpt()
        {
            // 保证我们的服务器，异常断开之后，可以立即重启，不会有bind问题
            int opt = 1;
            int n = ::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR,  &opt, sizeof(opt));
            (void)n;
        }

        virtual bool BindOrDie(int port) override
        {   
            if(_sockfd == gdefaultsockfd) return false;
            InetAddr addr(port);    
            int n = ::bind(_sockfd, addr.NetAddr(),addr.NetAddrLen());
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "bind socket failed";
                exit(BIND_ERR);
            }
            LOG(LogLevel::DEBUG) << "bind socket success";
            return true;            
        }


        virtual bool ListenOrDie()  override
        {
            if(_sockfd == gdefaultsockfd) return false;
            int n = ::listen(_sockfd, gbacklog);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "listen socket failed";
                exit(LISTEN_ERR);
            }
            LOG(LogLevel::DEBUG) << "listen socket success";
            return true;
        }


        virtual int Accepter(InetAddr *client)  override
        {
            if(!client) return -1;
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int newsockfd = ::accept(_sockfd, CONV(&peer), &len);
            if(newsockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept socket failed";
                return -1;
            }
            client->SetAddr(peer,len);
            return newsockfd;
            // return std::make_shared<TcpSocket>(newsockfd);
        }


        virtual void Close() override
        {
            if(_sockfd == gdefaultsockfd) return;
            ::close(_sockfd);
        }

        virtual int Recv(std::string *out)  override
        {
            char buffer[1024];
            auto size = ::recv(_sockfd,buffer,sizeof(buffer),0);
            if(size > 0)
            {
                buffer[size] = 0;
                *out = buffer;
            }

            return size;
        }

        virtual int Send(const std::string &in) override
        {
            auto size = ::send(_sockfd,in.c_str(),in.size(),0);
            return size;
        }

        virtual int fd() override
        {
            return _sockfd;
        }
    private:
        int _sockfd;
    };
}